package com.wy.w_ui.tab.bottom;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.FrameLayout;
import android.widget.ScrollView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.example.w_library.utils.DisplayUtil;
import com.example.w_library.utils.ViewUtil;
import com.wy.w_ui.R;
import com.wy.w_ui.tab.common.IWTabLayout;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class WTabBottomLayout extends FrameLayout implements IWTabLayout<WTabBottom,WTabBottomInfo<?>> {

    private List<OnTabSelectListener<WTabBottomInfo<?>>> tabSelectedChangeListener = new ArrayList<>();

    private WTabBottomInfo<?> selectedInfo;
    //背景透明度
    private float bottomAlpha = 1f;
    //高度
    private int tabBottomHeight = 50;
    //头部线条高度
    private int bottomLineHeight = 1;
    //头部线条颜色
    private String bottomLineColor = "#def0e1";
    //tab 集合
    private List<WTabBottomInfo<?>> infoList;
    //tab容器tag
    private static final String TAG_TAB_GROUP = "TAG_TAB_GROUP";

    public WTabBottomLayout(@NonNull Context context) {
        super(context);
    }

    public WTabBottomLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public WTabBottomLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public WTabBottom findTab(@NotNull WTabBottomInfo<?> wTabBottomInfo) {
        ViewGroup group = findViewWithTag(TAG_TAB_GROUP);

        for (int i = 0; i < group.getChildCount(); i++) {

            View child = group.getChildAt(i);
            if (child instanceof WTabBottom){
                WTabBottom tab = (WTabBottom) child;
                if (tab.getTabBottomInfo() == wTabBottomInfo){
                    return tab;
                }
            }
        }

        return null;
    }

    @Override
    public void addTabSelectChangeListener(OnTabSelectListener<WTabBottomInfo<?>> selectListener) {
        tabSelectedChangeListener.add(selectListener);
    }


    @Override
    public void defaultSelected(@NotNull WTabBottomInfo<?> defaultInfo) {
        onSelected(defaultInfo);
    }

    @Override
    public void inflateInfo(@NotNull List<WTabBottomInfo<?>> infoList) {

        if (infoList.isEmpty()){
            return;
        }

        this.infoList = infoList;

        //防止第二次调用的时候view 重复
        for (int i = getChildCount() - 1;i > 0;i--){
            removeViewAt(i);
        }
        selectedInfo = null;

        //清除之前添加的 tabSelectedChangeListener 监听,使用迭代器或者从后往前遍历,否则报错
        Iterator<OnTabSelectListener<WTabBottomInfo<?>>> iterable = tabSelectedChangeListener.iterator();
        while (iterable.hasNext()){
            // IWTab extends IWTabLayout.OnTabSelectListener ,WTabBottom implements IWTab
            //相当于 WTabBottom implements IWTabLayout.OnTabSelectListener
            if (iterable.next() instanceof WTabBottom){
                iterable.remove();
            }
        }

        //设置背景色
        addBackground();

        //创建 tab
        int width = DisplayUtil.deviceWidth(getContext()) / infoList.size();
        int height = DisplayUtil.dp2Px(getContext(),tabBottomHeight);
        //使用 LinearLayout 当动态改变 child 大小后 Gravity.BOTTOM 会失效
        FrameLayout tabGroup = new FrameLayout(getContext());
        tabGroup.setTag(TAG_TAB_GROUP);
        for (int i = 0; i < infoList.size(); i++) {

            final WTabBottomInfo<?> tabBottomInfo = infoList.get(i);

            LayoutParams params = new LayoutParams(width,height);
            params.gravity = Gravity.BOTTOM;
            params.leftMargin = i * width;

            WTabBottom tabBottom = new WTabBottom(getContext());
            //添加监听事件集合
            tabSelectedChangeListener.add(tabBottom);
            tabBottom.setTabInfo(tabBottomInfo);
            tabBottom.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    onSelected(tabBottomInfo);
                }
            });
            tabGroup.addView(tabBottom,params);

        }

        //添加分割线
        addBottomLIne();

        LayoutParams tabGroupParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        tabGroupParams.gravity = Gravity.BOTTOM;

        addView(tabGroup,tabGroupParams);

        fixContentView();
    }

    /**
     * 设置背景色
     */
    private void addBackground(){
        View view = LayoutInflater.from(getContext()).inflate(R.layout.tab_bottom_bg,null);
        LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DisplayUtil.dp2Px(getContext(),tabBottomHeight));
        layoutParams.gravity = Gravity.BOTTOM;
        addView(view,layoutParams);
        view.setAlpha(bottomAlpha);
    }


    /**
     * tab 被点击
     * @param nextInfo 当前点击的 Tab
     */
    private void onSelected(WTabBottomInfo<?> nextInfo){
        //遍历监听对象,挨个执行
        for (OnTabSelectListener<WTabBottomInfo<?>> listener : tabSelectedChangeListener) {
            listener.onTabSelectChange(infoList.indexOf(nextInfo),selectedInfo,nextInfo);
        }

        selectedInfo = nextInfo;
    }


    /**
     * 添加分割线
     */
    private void addBottomLIne(){

        View bottomLine = new View(getContext());
        bottomLine.setBackgroundColor(Color.parseColor(bottomLineColor));

        LayoutParams lineParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,DisplayUtil.dp2Px(getContext(),bottomLineHeight));
        lineParams.gravity = Gravity.BOTTOM;
        lineParams.bottomMargin = DisplayUtil.dp2Px(getContext(),tabBottomHeight - bottomLineHeight);
        addView(bottomLine,lineParams);

        bottomLine.setAlpha(bottomAlpha);
    }

    /**
     * 设置底部空出距离
     */
    private void fixContentView(){
        //非容器返回
        if (!(getChildAt(0) instanceof ViewGroup)){
            return;
        }

        ViewGroup rootView = (ViewGroup) getChildAt(0);

        ViewGroup targetView = ViewUtil.findTypeView(rootView, RecyclerView.class);

        if (targetView == null){
            targetView = ViewUtil.findTypeView(rootView, ScrollView.class);
        }

        if (targetView == null){
            targetView = ViewUtil.findTypeView(rootView, AbsListView.class);
        }

        if (targetView != null){
            targetView.setPadding(0,0,0, DisplayUtil.dp2Px(getContext(),tabBottomHeight));
            targetView.setClipToPadding(false);
        }
    }

    /**
     * 设置透明度
     * @param bottomAlpha
     */
    public void setTabAlpha(float bottomAlpha) {
        this.bottomAlpha = bottomAlpha;
    }

    /**
     * 设置高度
     * @param tabBottomHeight
     */
    public void setTabHeight(int tabBottomHeight) {
        this.tabBottomHeight = tabBottomHeight;
    }

    /**
     * 设置分割线高度
     * @param bottomLineHeight
     */
    public void setLineHeight(int bottomLineHeight) {
        this.bottomLineHeight = bottomLineHeight;
    }

    /**
     * 设置分割线颜色
     * @param bottomLineColor
     */
    public void setLineColor(String bottomLineColor) {
        this.bottomLineColor = bottomLineColor;
    }
}
